import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanzhende_app/common/api/activity_api.dart';
import 'package:wanzhende_app/common/models/index.dart';
import 'package:wanzhende_app/common/services/user_service.dart';
import 'dart:developer' as developer;

class ActivityApplicationMangementController extends GetxController {
  ActivityApplicationMangementController();

  // 待审核申请列表
  List<ParticipantEntity> pendingApplications = [];
  
  // 已处理申请列表
  List<ParticipantEntity> processedApplications = [];
  
  // 加载状态
  bool isLoading = false;
  String? errorMessage;

  /// 初始化数据
  _initData() {
    loadApplications();
  }

  /// 加载申请列表
  Future<void> loadApplications() async {
    final userId = UserService.to.currentUserProfile?.userid;
    if (userId == null) {
      errorMessage = '用户未登录';
      update(["activity_application_mangement"]);
      return;
    }

    isLoading = true;
    errorMessage = null;
    update(["activity_application_mangement"]);

    try {
      developer.log('🔄 开始加载活动申请列表');
      
      final response = await ActivityApi.getPublisherActivityParticipants(
        publisherId: userId,
      );

      if (response.isSuccess) {
        pendingApplications = response.pendingParticipants;
        processedApplications = [...response.approvedParticipants, ...response.rejectedParticipants];
        
        developer.log('✅ 申请列表加载成功');
        developer.log('⏳ 待审核: ${pendingApplications.length}');
        developer.log('✅ 已处理: ${processedApplications.length}');
      } else {
        errorMessage = response.message;
        developer.log('❌ 申请列表加载失败: ${response.message}');
      }
    } catch (e) {
      errorMessage = '加载申请列表失败: $e';
      developer.log('💥 加载申请列表异常: $e');
    } finally {
      isLoading = false;
      update(["activity_application_mangement"]);
    }
  }

  /// 审核申请（通过）
  Future<void> approveApplication(ParticipantEntity application) async {
    try {
      developer.log('🔄 开始通过申请');
      Get.snackbar(
        '处理中',
        '正在处理申请...',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.blue.withOpacity(0.8),
        colorText: Colors.white,
        duration: const Duration(seconds: 1),
      );
      
      final response = await ActivityApi.reviewParticipantApplication(
        activityId: application.activityId,
        userId: application.userId,
        reviewStatus: '通过',  // 🔥 必须使用中文（与小程序保持一致）
      );

      if (response.isSuccess) {
        Get.snackbar(
          '成功',
          '已通过申请',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
          duration: const Duration(seconds: 2),
        );
        developer.log('✅ 申请已通过');
        
        // 刷新列表
        await loadApplications();
      } else {
        Get.snackbar(
          '失败',
          '审核失败: ${response.message}',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red.withOpacity(0.8),
          colorText: Colors.white,
          duration: const Duration(seconds: 2),
        );
        developer.log('❌ 审核失败: ${response.message}');
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '审核失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
        duration: const Duration(seconds: 2),
      );
      developer.log('💥 审核申请异常: $e');
    }
  }

  /// 审核申请（拒绝）
  Future<void> rejectApplication(ParticipantEntity application, {String? note}) async {
    try {
      developer.log('🔄 开始拒绝申请');
      Get.snackbar(
        '处理中',
        '正在处理申请...',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.blue.withOpacity(0.8),
        colorText: Colors.white,
        duration: const Duration(seconds: 1),
      );
      
      final response = await ActivityApi.reviewParticipantApplication(
        activityId: application.activityId,
        userId: application.userId,
        reviewStatus: '未通过',  // 🔥 必须使用中文（与小程序保持一致）
        reviewNote: note,
      );

      if (response.isSuccess) {
        Get.snackbar(
          '成功',
          '已拒绝申请',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green.withOpacity(0.8),
          colorText: Colors.white,
          duration: const Duration(seconds: 2),
        );
        developer.log('✅ 申请已拒绝');
        
        // 刷新列表
        await loadApplications();
      } else {
        Get.snackbar(
          '失败',
          '审核失败: ${response.message}',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red.withOpacity(0.8),
          colorText: Colors.white,
          duration: const Duration(seconds: 2),
        );
        developer.log('❌ 审核失败: ${response.message}');
      }
    } catch (e) {
      Get.snackbar(
        '错误',
        '审核失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
        duration: const Duration(seconds: 2),
      );
      developer.log('💥 审核申请异常: $e');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }
}
